package com.aube.interact;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aube.interact.model.GoodsItem;
import com.aube.interact.util.Utils;
import com.aube.rvi.CommonDataLoader;
import com.aube.rvi.util.StringUtils;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/3/22.
 */
public class FavorList extends LinearLayout {

    private View mRoot;

    private ImageView mFavorIcon, mFavorDes;
    private View mDivider, mBg, mTool;
    private ScrollView mScrollView;
    private LinearLayout mContent;

    private BadgeView mBadgeView;

    public FavorList(Context context) {
        this(context, null);
    }

    public FavorList(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FavorList(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mRevealPath = new Path();

        mRoot = LayoutInflater.from(getContext()).inflate(R.layout.aube_plugin_layout_card_goodslist, this);

        mFavorIcon = (ImageView) findViewById(R.id.list_icon);
        mFavorDes = (ImageView) findViewById(R.id.list_des);
        mDivider = findViewById(R.id.list_divider);
        mBg = findViewById(R.id.list_bg);
        mScrollView = (ScrollView) findViewById(R.id.list_scroll);
        mContent = (LinearLayout) findViewById(R.id.list_content);
        mTool = findViewById(R.id.list_tool);
        mBadgeView = (BadgeView) findViewById(R.id.list_badge);

        displayFavorList(false, true);
    }

    public void initClickEvent(final ICartClickListener listener) {
        mFavorIcon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null)
                    listener.onClicked();
                if (mBg.getVisibility() == View.VISIBLE) {
//                    displayFavorList(false, false);
//                    revealAanim(false);
                    hideList();
                } else {
                    displayFavorList(true, false);
//                    revealAanim(true, null);
                    showList();

                    if(listener != null)
                        listener.hideGoods();
                }
            }
        });
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public int getIconWidth() {
        int iconWidth = mFavorIcon.getWidth();
        return iconWidth == 0 ? 150 : iconWidth;
    }

    public void addItems(List<GoodsItem> data, boolean executeHide) {
        if(data == null || data.size() == 0)
            return;
        boolean isVisible = getVisibility() == View.VISIBLE;
        setVisibility(View.VISIBLE);

        for(final GoodsItem item : data) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.aube_plugin_item_goods, null);

            ImageView mLogo = (ImageView) view.findViewById(R.id.goods_logo);
            TextView mDes = (TextView) view.findViewById(R.id.goods_des);
            TextView mOperator = (TextView) view.findViewById(R.id.goods_operator);
            View mDivider = view.findViewById(R.id.goods_divider);

            mContent.addView(view);

            view.setTag(item._id);

            if (mContent.getChildCount() == 1)
                mDivider.setVisibility(View.GONE);
            else
                mDivider.setVisibility(View.VISIBLE);

            //setcontent
            CommonDataLoader.getInstance(getContext()).startImageLoader(mLogo, item.picurl, 200, 200);
            mDes.setText(item.tlTitle);

            mOperator.setText(item.goodstypedesc);
            mOperator.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showGetGoodsDialog(item.goodsURL);
                }
            });
        }

        itemHeight = Utils.dip2px(getContext(), 60);

        sizeFixed = false;

        if(mBg.getVisibility() == VISIBLE)
            displayFavorList(true, false);

        requestLayout();

        int size = mContent.getChildCount();

        mBadgeView.setText(size);

        if(executeHide && !isVisible)
            animShowCart();
    }

    public void addItem(final GoodsItem data, boolean executeHide) {
        if(data == null)
            return;
        boolean isVisible = getVisibility() == View.VISIBLE;
        setVisibility(View.VISIBLE);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.aube_plugin_item_goods, null);

        ImageView mLogo = (ImageView) view.findViewById(R.id.goods_logo);
        TextView mDes = (TextView) view.findViewById(R.id.goods_des);
        TextView mOperator = (TextView) view.findViewById(R.id.goods_operator);
        View mDivider = view.findViewById(R.id.goods_divider);

        mContent.addView(view);

        view.setTag(data._id);

        if(mContent.getChildCount() == 1)
            mDivider.setVisibility(View.GONE);
        else
            mDivider.setVisibility(View.VISIBLE);

        //setcontent

//        CommonDataLoader.getInstance(getContext()).startImageLoaderWithDefaultImg(mLogo, data.picturl);
        CommonDataLoader.getInstance(getContext()).startImageLoader(mLogo, data.picurl, 200, 200);
        mDes.setText(data.tlTitle);

        mOperator.setText(data.goodstypedesc);
        mOperator.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showGetGoodsDialog(data.goodsURL);
            }
        });

        itemHeight = Utils.dip2px(getContext(), 60);

        sizeFixed = false;

        if(mBg.getVisibility() == VISIBLE)
            displayFavorList(true, false);

        requestLayout();

        int size = mContent.getChildCount();

        mBadgeView.setText(size);

        if(executeHide && !isVisible)
            animShowCart();
    }

    public void remove(String id) {
        if(StringUtils.isBlank(id))
            return;

        View view = mContent.findViewWithTag(id);
        mContent.removeView(view);

        if(mContent.getChildCount() == 0) {
//            setVisibility(View.GONE);
        } else {
            for(int i=0; i<mContent.getChildCount(); i++)
                mContent.getChildAt(0).findViewById(R.id.goods_divider).setVisibility(i == 0 ? View.GONE : View.VISIBLE);
        }

        itemHeight = Utils.dip2px(getContext(), 60);

        sizeFixed = false;

        if(mBg.getVisibility() == VISIBLE)
            displayFavorList(true, false);

        requestLayout();

        int size = mContent.getChildCount();

        if(getVisibility() == View.VISIBLE)
            mBadgeView.setText(size);
    }

    /**
     * 当添加物品到购物车的时候,把购物车暂时显示出来,然后再隐藏掉
     */
    private void animShowCart() {
        ObjectAnimator ani = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f);
        ani.setDuration(300);

        ani.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationStart(Animator animation) {
                manageVisible(false, true);
            }
        });

        ani.start();
    }

    private void hideCart() {
//        if(getVisibility() == View.GONE)
//            return;
        ObjectAnimator ani = ObjectAnimator.ofFloat(this, "alpha", 1f, 0f);
        ani.setDuration(300);

        ani.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                manageVisible(false, false);
            }
        });

        ani.start();
    }

    public void manageVisible(boolean fromMain, boolean visible) {
        if(visible && mContent != null && mContent.getChildCount() > 0)
            setVisibility(View.VISIBLE);
        else
            setVisibility(View.GONE);

        if(fromMain)
            displayFavorList(false, false);
    }

    private boolean sizeFixed = false;
    private int itemHeight = 0;

    public boolean isShowing() {
        return getVisibility() == View.VISIBLE && mBg.getVisibility() == View.VISIBLE;
    }

    public void displayFavorList(boolean display, boolean auto) {
        if(display) {
            //展示列表
            mFavorDes.setVisibility(View.VISIBLE);
            mDivider.setVisibility(View.VISIBLE);
            mBg.setVisibility(View.VISIBLE);
            mScrollView.setVisibility(View.VISIBLE);

            mFavorIcon.setImageResource(R.drawable.icon_cart_1);

            if(!sizeFixed && !auto) {
                int count = mContent.getChildCount();
                int fiexedHeight = itemHeight*count + mTool.getHeight();

                int containerHeight = getHeight();

                ViewGroup.LayoutParams params = mBg.getLayoutParams();
                params.height = fiexedHeight > containerHeight ? containerHeight : fiexedHeight;

                ViewGroup.LayoutParams paramsScroll = mScrollView.getLayoutParams();
                paramsScroll.height = fiexedHeight > containerHeight ? (containerHeight - mTool.getHeight()) : (fiexedHeight - mTool.getHeight());

                sizeFixed = true;
            }
        } else {
            //隐藏列表
            mFavorDes.setVisibility(View.GONE);
            mDivider.setVisibility(View.INVISIBLE);
            mBg.setVisibility(View.GONE);
            mScrollView.setVisibility(View.GONE);

            mFavorIcon.setImageResource(R.drawable.icon_cart_2);
        }
    }

    private Path mRevealPath;
    private AtomicBoolean mRunning = new AtomicBoolean(false);
    private int centerX=0, centerY=0;
    private int mRadius = 0;
    @Override
    protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
        if(mRunning.get()){
            final int state = canvas.save();

            mRevealPath.reset();
            mRevealPath.addCircle(centerX, centerY, mRadius, Path.Direction.CW);

            canvas.clipPath(mRevealPath);

            boolean isInvalided = super.drawChild(canvas, child, drawingTime);

            canvas.restoreToCount(state);

            return isInvalided;
        }

        return super.drawChild(canvas, child, drawingTime);
    }

    private void toggleAnim(boolean running) {
        mRunning.set(running);
    }

    private void reveal(boolean show, final int fromRadius, final int endRadius, Animator.AnimatorListener listener) {
        if(mRunning.get())
            return;
        toggleAnim(true);
        float start = show ? 0 : 1;
        float end = show ? 1 : 0;
        ValueAnimator anim = ValueAnimator.ofFloat(start, end);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float fraction = (float) animation.getAnimatedValue();

                mRadius = (int) (fromRadius + (endRadius-fromRadius)*fraction);

                invalidate();
            }
        });
        if(listener == null) {
            anim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    toggleAnim(false);
                }
            });
        } else {
            anim.addListener(listener);
        }
        anim.setDuration(500);
        anim.start();
    }

    private int getFinalRaius(int x, int y) {
        int[] locations = new int[2];
        mBg.getLocationOnScreen(locations);

        int topY = locations[1];
        int topX = locations[0] + getWidth();

//        int height = SysUtil.getAbsoluteScreenHeight(getContext());
//
//        double xy = Math.hypot(getWidth(), getHeight() - (mAnchor!=null?mAnchor.getHeight():0));

        return (int) Math.hypot(Math.abs(x-topX), Math.abs(y-topY)) - 50;
    }

    private void showList() {
        if(mRunning.get())
            return;
        int[] location = new int[2];
        mFavorIcon.getLocationOnScreen(location);
        centerX = location[0] + mFavorIcon.getWidth()/2;
        centerY = location[1] + mFavorIcon.getHeight()/2 - getOffset();
        int fromRadius = mFavorIcon.getWidth()/2;
        int endRadius = getFinalRaius(location[0] + mFavorIcon.getWidth()/2, location[1] + mFavorIcon.getHeight()/2);

        reveal(true, fromRadius, endRadius, null);
    }

    public void hideList() {
        if(mRunning.get())
            return;
        int[] location = new int[2];
        mFavorIcon.getLocationOnScreen(location);
        centerX = location[0] + mFavorIcon.getWidth()/2;
        centerY = location[1] + mFavorIcon.getHeight()/2 - getOffset();
        int endRadius = mFavorIcon.getWidth()/2;
        int fromRadius = getFinalRaius(location[0] + mFavorIcon.getWidth()/2, location[1] + mFavorIcon.getHeight()/2);
        reveal(true, fromRadius, endRadius, new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                toggleAnim(false);
                displayFavorList(false, false);
            }
        });
    }

    private View mAnchor;
    public void setAnchor(View view) {
        mAnchor = view;
    }

    public int getOffset() {
        if(mAnchor == null || mAnchor.getVisibility() != View.VISIBLE)
            return 0;
        return mAnchor.getHeight();
    }

    public void showGetGoodsDialog(final String url){
        if(StringUtils.isBlank(url)) {
            Utils.showToast(getContext(), "链接无效");
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext(), R.style.AlertDialog);
        builder.setTitle("将会退出视频,您可在视频结束后统一查看领取");
        builder.setNegativeButton(R.string.btn_open,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //do something
                    }
                });
        builder.setPositiveButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        Dialog dialog = builder.create();
        dialog.show();
    }

    public interface ICartClickListener {
        public void onClicked();
        public void hideGoods();
    }

}
